package com.cyb.binojcodesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.cyb.binojcodesandbox.model.ExecuteCodeRequest;
import com.cyb.binojcodesandbox.model.ExecuteCodeResponse;
import com.cyb.binojcodesandbox.model.ExecuteMessage;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate {
    private static final long TIME_OUT = 5000L;
    private static volatile Boolean FIRST_INIT = true;

    /**
     * 创建容器，把文件复制到容器内
     * @param userCodeFile
     * @param inputList
     * @return
     */
    @Override
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        //3.创建容器，把文件复制到容器内
        //获取默认的Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        //拉取镜像
        String image = "openjdk:8-alpine";
        //判断镜像是否存在，是否要下载
        if(FIRST_INIT){
            isImageExists(dockerClient, image);
            FIRST_INIT = false;
        }
        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        //创建容器映射。容器挂载目录
        HostConfig hostConfig = new HostConfig();
        //限制最大内存
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                //设置容器的主机配置，包括资源限制、网络配置、挂载点等
                .withHostConfig(hostConfig)
                //设置网络配置禁用
                .withNetworkDisabled(true)
                //将标准输入(STDIN)附加到容器，允许向容器发送输入数据
                .withAttachStdin(true)
                //禁止用户向root根目录写文件
                .withReadonlyRootfs(true)
                //将标准错误(STDERR)附加到容器，用于捕获错误输出
                .withAttachStderr(true)
                //将标准输出(STDOUT)附加到容器，用于捕获正常输出
                .withAttachStdout(true)
                //为容器分配一个伪TTY终端，提供交互式shell体验
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();
        //docker exec boring_ptolemy java -cp /app Main 1 3
        //执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("执行创建命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final StringBuilder messageBuilder = new StringBuilder();
            final StringBuilder errorMessageBuilder = new StringBuilder();
            long time = 0l;
            //判断超时
            final boolean[] timeOut = {true};
            String execId = execCreateCmdResponse.getId();
            //创建线程同步辅助类
            final CountDownLatch latch = new CountDownLatch(1);
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    timeOut[0] = false;
                    latch.countDown();
                    // 打印完整输出
                    System.out.println("程序执行完成，标准输出：" + messageBuilder.toString());
                    System.out.println("程序执行完成，错误输出：" + errorMessageBuilder.toString());
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        String chunk = new String(frame.getPayload());
                        errorMessageBuilder.append(chunk);
                        System.out.println("输出错误结果：" + chunk);
                    } else {
                        String chunk = new String(frame.getPayload());
                        messageBuilder.append(chunk);
                        System.out.println("输出结果：" + chunk);
                    }
                    super.onNext(frame);
                }
            };
            final long[] maxMemory = {0l};
            //获取占用内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onStart(Closeable closeable) {

                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback);
                        //.awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                System.out.println(messageBuilder.toString().trim());
                statsCmd.close();
                if (!latch.await(TIME_OUT, TimeUnit.MILLISECONDS)) {
                    System.out.println("等待超时");
                }
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                System.out.println(time);
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(messageBuilder.toString().trim());
            executeMessage.setErrorMessage(errorMessageBuilder.toString().trim());
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        // 删除容器
        try {
            dockerClient.removeContainerCmd(containerId)
                    .withForce(true)
                    .exec();
            System.out.println("容器已删除: " + containerId);
        } catch (Exception e) {
            System.err.println("删除容器失败: " + e.getMessage());
        }

        return executeMessageList;
    }

    /**
     * 判断镜像是否存在
     * @param dockerClient
     * @param imageName
     * @return
     */
    private void isImageExists(DockerClient dockerClient, String imageName) {
            List<Image> images = dockerClient.listImagesCmd()
                    .withImageNameFilter(imageName)
                    .exec();
            if(images.isEmpty()){
                PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
                //创建回调处理拉取过程中的状态更新
                PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                    @Override
                    public void onNext(PullResponseItem item) {
                        System.out.println("下载镜像" + item.getStatus());
                        super.onNext(item);
                    }
                };
                try {
                    pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
                    FIRST_INIT = false;
                } catch (InterruptedException e) {
                    System.out.println("拉取镜像异常");
                    throw new RuntimeException(e);
                }
                System.out.println("下载完成");
            }
    }
}
